package com.itheima.mm.wx.service.impl;

import com.itheima.framework.annotation.HmComponent;
import com.itheima.mm.database.MmDaoException;
import com.itheima.mm.database.SqlSessionUtils;
import com.itheima.mm.pojo.WxMember;
import com.itheima.mm.wx.dao.WxMemberDao;
import com.itheima.mm.wx.service.WxMemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import java.util.Map;

/**
 * @author ：wanghao
 * @date ：Created in 2020/11/2
 * @description ：微信会员业务实现类
 * @version: 1.0
 */
@HmComponent("wxMemberService")
@Slf4j
public class WxMemberServiceImpl implements WxMemberService {
    @Override
    public WxMember findWxMemberByOpenId(String openid) {
        SqlSession sqlSession = SqlSessionUtils.openSession();
        WxMemberDao wxMemberDao = sqlSession.getMapper(WxMemberDao.class);
        WxMember wxMember = wxMemberDao.selectWxMemberByOpenId(openid);
        sqlSession.close();
        return wxMember;
    }

    @Override
    public void regWxMember(WxMember wxMember) {
        SqlSession sqlSession = SqlSessionUtils.openSession();
        try {
            WxMemberDao wxMemberDao = sqlSession.getMapper(WxMemberDao.class);
            wxMemberDao.insertWxMember(wxMember);
            sqlSession.commit();
            sqlSession.close();
        }catch (MmDaoException e){
            sqlSession.rollback();
            sqlSession.close();
            e.printStackTrace();
            log.error(e.getMessage());
            throw new MmDaoException(e.getMessage());
        }
    }

    @Override
    public void updateCityCourse(Map data) {
        SqlSession sqlSession = SqlSessionUtils.openSession();
        try {
            WxMemberDao wxMemberDao = sqlSession.getMapper(WxMemberDao.class);
            wxMemberDao.updateCityCourse(data);
            sqlSession.commit();
            sqlSession.close();
        }catch (MmDaoException me){
            sqlSession.rollback();
            sqlSession.close();
            me.printStackTrace();
            log.error(me.getMessage());
            throw new MmDaoException(me.getMessage());
        }
    }

    @Override
    public Map<String, Object> findUserCenterById(int id) {
        try {
            // 调用Dao，获取会员中心数据
            SqlSession sqlSession = SqlSessionUtils.openSession();
            WxMemberDao wxMemberDao = sqlSession.getMapper(WxMemberDao.class);
            Map map = wxMemberDao.selectUserCenterById(id);
            String categoryTitle = wxMemberDao.selectCategoryTitleByCategory((Integer)map.get("categoryKind"),(Integer)map.get("categoryID"));
            map.put("categoryTitle",categoryTitle);
            sqlSession.close();
            return map;
        }catch (MmDaoException e){
            e.printStackTrace();
            log.error(e.getMessage());
            throw new MmDaoException(e.getMessage());
        }
    }
}
